import 'package:flutter/material.dart';
import 'package:talk/api/UserApi.dart';

import '../../api/dio/DioClient.dart';
import '../../res/dimens.dart';
import '../../routers/fluro_navigator.dart';
import '../../src/widgets/click_item.dart';
import '../../tools/widgets/load_image.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../tools/widgets/my_button.dart';
import '../../tools/widgets/my_scroll_view.dart';
import '../../tools/widgets/selected_image.dart';
import '../../tools/widgets/text_field_item.dart';
import '../../../utils/toast_utils.dart';
import '../login/login_router.dart';

/// design/8设置/index.html#artboard1
class AccountManagerPage extends StatefulWidget {

  // const AccountManagerPage({super.key});
  const AccountManagerPage({
    super.key,
    this.heroTag,
    this.goodsImageUrl
  });

  final String? goodsImageUrl;
  final String? heroTag;

  @override
  _AccountManagerPageState createState() => _AccountManagerPageState();
}

class _AccountManagerPageState extends State<AccountManagerPage> {

  final UserApi _userApi = UserApi();
  String avatar = '';
  String? _displayImageUrl; // 添加状态变量来保存显示的图片URL


  // 表单数据和初始值
  final Map<String, dynamic> _formData = {
    'description': '',
    'description2': '',
    'discount': 0,
  };


  //初始化数据
  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      final response = await _userApi.getInfoData();

      if (response.code == 200) {
        final dataMap = response.data as Map<String, dynamic>;
        final avatarData = dataMap['avatar']; // 访问具体属性
        if(avatarData != ''){
          setState(() {
            avatar = DioClient.baseUrl + avatarData;
            _displayImageUrl = avatar; // 更新状态变量
          });
        }

        // 初始化表单数据和初始值
        _formData['description'] = dataMap['description'] ?? '120000'; // 默认值
        _formData['description2'] = dataMap['description2']?.toString() ?? '';
        _formData['discount'] = dataMap['discount'] ?? 0;

      } else {
        Toast.show('接口500异常');
      }
    } catch (e) {
      // 处理异常
      Toast.show('网络错误，请检查网络连接');
    }
  }

  // 新增：提交表单方法
  Future<void> _submitForm() async {
    // 调用更新接口
    final response = await _userApi.updateUserInfo(_formData);

    if(response.code == 200){
      Toast.show('提交成功');
      // 返回上一页
      NavigatorUtils.goBack(context);

    }else{
      Toast.show('提交失败');
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: const MyAppBar(
          centerTitle: '账号管理',
        ),

        body: MyScrollView(
            key: const Key('goods_edit_page'),
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            bottomButton: Padding(
              padding: const EdgeInsets.only(left: 16.0, right: 16.0, bottom: 8.0),
              child: MyButton(
                // 修改：调用提交表单方法
                onPressed: _submitForm,
                text: '提交',
              ),
            ),
            children: <Widget>[
              Column(
                children: <Widget>[
                  Stack(
                    children: <Widget>[
                      Center(
                        child: SelectedImage(
                          heroTag: widget.heroTag,
                          url: _displayImageUrl, // 使用状态变量
                          size: 96.0,
                        ),
                      ),
                    ],
                  ),
                  ClickItem(
                      title: '修改密码',
                      content: '用于密码登录',
                      onTap: () => NavigatorUtils.push(context, LoginRouter.updatePasswordPage)
                  ),
                  const ClickItem(
                    title: '绑定账号',
                    content: '15000000000',
                  ),


                  // 修改：使用表单字段
                  TextFieldItem(
                    title: '商品说明',
                    hintText: _displayImageUrl ?? '',
                    xunText: _formData['description'],
                    onXunTextChanged: (value) {
                      _formData['description'] = value;
                    },
                    xunTextStyle: TextStyle(
                        color: Colors.black,
                        fontSize: 16.0,
                        height: 1.65
                    ),
                  ),
                  TextFieldItem(
                    title: '商品说明2',
                    hintText: _displayImageUrl ?? '',
                    onXunTextChanged: (value) {
                      _formData['description2'] = value;
                    },
                  ),
                  TextFieldItem(
                    title: '折扣金额',
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    onXunTextChanged: (value) {
                      // 将字符串转换为整数（忽略小数部分）
                      _formData['discount'] = int.tryParse(value) ?? 0;
                    },
                  ),
                ],
              ),
            ]
        )
    );
  }
}